package com.sheep.juc;

import org.junit.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangze
 * @date 2020-10-17 16:34.
 **/
public class Account {
	public final Lock lock=new ReentrantLock();
	private int balance;
	public  Account(int balance){
		this.balance=balance;
	}

	public void  transfer(Account b,int balance) {
		while (true){
			try{
				if(lock.tryLock(1, TimeUnit.MILLISECONDS)){
					try {
						if(b.lock.tryLock(2,TimeUnit.MILLISECONDS)){
							if(balance<this.balance){
								this.balance-=balance;
								b.balance+=balance;
								break;
							}else{
								throw new RuntimeException("转出金额大于金额");
							}
						}
					}
					catch (InterruptedException ex){
						Thread.currentThread().interrupt();
					}
					finally {
						lock.unlock();
					}

				}
			}
			catch (InterruptedException ex){
				Thread.currentThread().interrupt();
			}
			finally {
				lock.unlock();
			}

		}
	}


	@Test
	public void  testTransfer(){

	}
}
